package cn.ztydata.teachingsystem.heaven.web.controller;

import cn.ztydata.teachingsystem.common.Page;
import cn.ztydata.teachingsystem.heaven.cons.GroupType;
import cn.ztydata.teachingsystem.heaven.cons.MsgTemplate;
import cn.ztydata.teachingsystem.heaven.entity.*;
import cn.ztydata.teachingsystem.heaven.entity.Class;
import cn.ztydata.teachingsystem.heaven.service.ClassGroupService;
import cn.ztydata.teachingsystem.heaven.service.CourseGroupService;
import cn.ztydata.teachingsystem.heaven.service.ResourceService;
import cn.ztydata.teachingsystem.heaven.service.SpecialtyGroupService;
import cn.ztydata.teachingsystem.heaven.web.dto.ClassDto;
import cn.ztydata.teachingsystem.heaven.web.dto.ClassGroup.StudentInfoDto;
import cn.ztydata.teachingsystem.heaven.web.dto.CourseGroupDto;
import cn.ztydata.teachingsystem.heaven.web.dto.CourseInfoDto;
import cn.ztydata.teachingsystem.heaven.web.dto.SpecialtyGroup.SpecialtyInfoDto;
import cn.ztydata.teachingsystem.heaven.web.wrapper.HttpSessionProxy;
import cn.ztydata.teachingsystem.util.StringCodeUtil;
import cn.ztydata.teachingsystem.webservice.result.json.JsonResult;
import cn.ztydata.teachingsystem.webservice.result.json.JsonResultData;
import cn.ztydata.teachingsystem.webservice.result.json.JsonResultList;
import cn.ztydata.teachingsystem.webservice.result.json.JsonResultPage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.MessageFormat;
import java.util.List;
import java.util.Map;

/**
 * 群组控制器
 *
 * @author lyj
 * @since 2015/3/30
 */
@Controller
@RequestMapping("/group")
public class GroupController extends BaseController{
    @Autowired
    private CourseGroupService courseGroupService;
    @Autowired
    private ClassGroupService classGroupService;
    @Autowired
    private SpecialtyGroupService specialtyGroupService;
    @Autowired
    private ResourceService resourceService;

    @Value("${session.key}")
    private String sessionKey;

    //<editor-fold "课程群组">
    /**
     * 获取当前学期课程群组
     *
     * @param pageNum 当前页码
     * @param pageSize 每页条数
     * @return JsonResultList
     * @author lyj
     * @since 2015-3-30
     */
    @RequestMapping(value = "/myLessonList", method = RequestMethod.GET)
    @ResponseBody
    public JsonResultPage getSemester(@RequestParam("page") int pageNum,
                                      @RequestParam("pageSize") int pageSize,
                                      @RequestParam(value = "keyword", required = false) String keyword){
        Assert.isTrue(pageNum > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "当前页码"));
        Assert.isTrue(pageSize > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "每页条数"));
        Assert.notNull(keyword.trim(), MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "关键字"));

        keyword = StringCodeUtil.urlParamTransCode(keyword, "utf-8"); //汉字转码

        Page<CourseGroup> page = courseGroupService.getSemester(pageNum, pageSize, keyword);

        log.debug("获取当前学期课程群组");
        return new JsonResultPage(new Page(page.getTotal(), pageSize, pageNum, mapper.mapList(page.getItems(), CourseGroupDto.class)));

    }

    /**
     * 获取历史课程群组列表
     *
     * @param startYear 开始学年
     * @param term 学期
     * @param pageNum 当前页码
     * @param pageSize 每页条数
     * @return JsonResultPage
     * @author lyj
     * @since 2015-3-31
     */
    @RequestMapping(value = "/myHistoryLessonList/{startYear}/{term}", method = RequestMethod.GET)
    @ResponseBody
    public JsonResultPage getHistory(@PathVariable("startYear") String startYear,
                                     @PathVariable("term") int term,
                                     @RequestParam("page") int pageNum,
                                     @RequestParam("pageSize") int pageSize,
                                     @RequestParam(value = "keyword", required = false) String keyword) {
        Assert.notNull(startYear, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "起始年份"));
        Assert.isTrue(term >= 0 && term < 3, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "学期"));
        Assert.isTrue(pageNum > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "当前页码"));
        Assert.isTrue(pageSize > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "每页条数"));
        Assert.notNull(keyword.trim(), MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "关键字"));

        keyword = StringCodeUtil.urlParamTransCode(keyword, "utf-8"); //汉字转码

        Page<CourseGroup> page = courseGroupService.getHistory(startYear, term, pageNum, pageSize, keyword);

        log.debug("获取历史课程群组列表");
        return new JsonResultPage(new Page(page.getTotal(), pageSize, pageNum, mapper.mapList(page.getItems(), CourseGroupDto.class)));

    }

    /**
     * 获取课程明细
     *
     * @param groupId 群组ID
     * @param courseId 课程ID
     * @return JsonResultData
     * @author lyj
     * @since 2015-3-31
     */
    @RequestMapping(value = "/lessonInfo", method = RequestMethod.GET)
    @ResponseBody
    public JsonResultData getDetail(@RequestParam("groupId") long groupId,
                                    @RequestParam("lessonId") long courseId,
                                    @RequestParam("groupType") int type,
                                    HttpServletRequest request) {
        Assert.isTrue(groupId > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "群组ID"));
        Assert.isTrue(courseId > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "课程ID"));

        //获取登录用户信息
        User userInfo = (User)((HttpSessionProxy)request.getSession()).getAttribute(sessionKey);

        Course course = courseGroupService.getDetail(courseId, groupId, type, userInfo);

        if (course == null) {
            return new JsonResultData(false, null);
        }

        log.debug("获取课程明细");
        return new JsonResultData(mapper.map(course, CourseInfoDto.class));
    }

    /**
     * 获取历史学期下拉列表
     *
     * @return List
     * @author lyj
     * @since 2015-3-31
     */
    @RequestMapping(value = "/startYearCombo")
    @ResponseBody
    public JsonResultList getStartYear(HttpServletRequest request) {
        //获取登录用户信息
        User userInfo = (User)((HttpSessionProxy)request.getSession()).getAttribute(sessionKey);

        log.debug("获取历史学期下拉列表");
        return new JsonResultList(courseGroupService.getStartYear(userInfo.getNumber()));
    }

    /**
     * 课程群组列表
     * @param departCode 系部编码
     * @param startYear 起始学年 ""：当前 "0"：全部历史群组 "2015"：2015-2016
     * @param term 学期 0：上 1：下 2：全部
     * @param page 页码
     * @param pageSize 页数
     * @return Page
     *
     * @author wyh
     * @since 2015-03-30
     */
    @RequestMapping(value = "/lessonList", method = RequestMethod.GET)
    @ResponseBody
    public JsonResultPage<CourseGroup> listGroup(@RequestParam(value = "departCode", required = false) String departCode,
                                                 @RequestParam("startYear") String startYear,
                                                 @RequestParam("term") int term,
                                                 @RequestParam("page") int page,
                                                 @RequestParam("pageSize") int pageSize) {
        //校验
        Assert.notNull(startYear, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "起始学年"));
        Assert.isTrue(term >= 0 && term <= 2, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "学期"));
        Assert.isTrue(page > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "当前页码"));
        Assert.isTrue(pageSize > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "每页条数"));

        if(StringUtils.isEmpty(startYear)){
            log.debug("返回 当前课程群组列表");
            return new JsonResultPage<>(courseGroupService.listGroup(departCode, page, pageSize));
        } else {
            //调整数据
            if(startYear.equals("0")){
                log.debug("学年为0：startYear.equals(\"0\")");
                startYear = "";
            }
            log.debug("返回 历史课程群组列表");
            return new JsonResultPage<>(courseGroupService.listHistoryGroup(departCode, startYear, term, page, pageSize));
        }
    }

    /**
     * 课程群组下拉框
     * @param type 身份（0：教师，1：学生）
     * @param request 请求
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2015-04-06
     */
    @ResponseBody
    @RequestMapping(value = "/lessonGroupCombo/{type}")
    public JsonResult lessonGroupCombo(@PathVariable int type,HttpServletRequest request){
        //获取登录用户信息
        User userInfo = (User)((HttpSessionProxy)request.getSession()).getAttribute(sessionKey);

        List<CourseGroup> courseGroups = courseGroupService.getForTeacherAndStudent(type,userInfo);

        return new JsonResultList<>(mapper.mapList(courseGroups,CourseGroupDto.class));
    }


    /**
     * 获取登录人是否可以获取指定群组的信息
     * @param request
     * @return list
     * @author lyj
     * @since 2015-4-23
     */
    @RequestMapping(value = "/getAllGroupIds", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult checkGroupId(@RequestParam("groupId") long groupId,
                                       @RequestParam("groupType") int groupType,
                                       HttpServletRequest request) {
        //获取登录用户信息
        User userInfo = (User)((HttpSessionProxy)request.getSession()).getAttribute(sessionKey);

        if (courseGroupService.getAllGroupIds(groupId, groupType, userInfo)) {
            return new JsonResult(true, "");
        }

        return new JsonResult(false, "权限错误！");
    }


    /**
     * 课程群组资源统计
     * @param search 搜索关键字
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2015-05-06
     */
    @RequestMapping(value = "/courseResourceStatistics", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult courseResourceStatistics(@RequestParam String search,@RequestParam int tag){
        Assert.isTrue(tag == 0 || tag == 1,MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "标记"));

        //搜索关键字转码
        search = StringCodeUtil.urlParamTransCode(search, "utf-8");

        List<Map<String, Object>> groupResource = resourceService.getGroupResourceStatistics(tag, GroupType.COURSE_GROUP, search);

        return new JsonResultList<>(groupResource);
    }
    //</editor-fold>


    //<editor-fold "班级群组">

    /**
     * 班级群组列表
     * @param tag 标记 0当前 1历史
     * @param search 关键字
     * @return list
     * @author lyj
     * @since 2015-5-5
     */
    @RequestMapping(value = "/classList", method = RequestMethod.GET)
    @ResponseBody
    public JsonResultPage getAllClasses(@RequestParam("page") int pageNum,
                                        @RequestParam("pageSize") int pageSize,
                                        @RequestParam("tag") int tag,
                                        @RequestParam(value = "search", required = false, defaultValue = "") String search,
                                        HttpServletRequest request) {
        Assert.isTrue(pageNum > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "当前页码"));
        Assert.isTrue(pageSize > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "每页条数"));
        Assert.isTrue(tag == 0 || tag == 1, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "tag标记"));

        search = StringCodeUtil.urlParamTransCode(search, "utf-8"); //汉字转码
        //获取登录用户信息
        User userInfo = (User)((HttpSessionProxy)request.getSession()).getAttribute(sessionKey);

        Page<Class> page = classGroupService.getAllClasses(pageNum, pageSize, tag, search, userInfo.getNumber());

        log.debug("1.班级群组列表");
        return new JsonResultPage(new Page(page.getTotal(), pageSize, pageNum, mapper.mapList(page.getItems(), ClassDto.class)));
    }


    /**
     * 获取班级群组明细头部信息
     * @param classId 班级ID
     * @param tag 标记0当前 1历史
     * @return JsonResultData
     * @author lyj
     * @since 2015-5-5
     */
    @RequestMapping(value = "/classTop", method = RequestMethod.GET)
    @ResponseBody
    public JsonResultData getClassTop(@RequestParam("id") long classId,
                                      @RequestParam("tag") int tag,
                                      HttpServletRequest request) {
        Assert.isTrue(classId > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "班级ID"));
        Assert.isTrue(tag == 0 || tag == 1, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "tag标记"));

        //获取登录用户信息
        User userInfo = (User)((HttpSessionProxy)request.getSession()).getAttribute(sessionKey);

        Class classe = classGroupService.getClassTop(classId, tag, userInfo);

        if (classe != null) {
            log.debug("班级不为NULL,classe != null");
            return new JsonResultData(mapper.map(classe, ClassDto.class));
        }

        log.debug("获取班级群组明细头部信息");
        return new JsonResultData(false, "获取班级群组明细失败！");
    }

    /**
     * 班级群组资源统计
     * @param search 搜索关键字
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2015-05-06
     */
    @RequestMapping(value = "/classResourceStatistics", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult classResourceStatistics(@RequestParam String search,@RequestParam int tag){

        Assert.isTrue(tag == 0 || tag == 1,MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "标记"));

        //搜索关键字转码
        search = StringCodeUtil.urlParamTransCode(search, "utf-8");

        List<Map<String,Object>> groupResource = resourceService.getGroupResourceStatistics(tag, GroupType.CLASS_GROUP, search);

        return new JsonResultList<>(groupResource);
    }

    //</editor-fold>


    //<editor-fold "专业群组">

    /**
     * 获取专业群组列表
     *
     * @param pageNum 当前页码
     * @param pageSize 每页条数
     * @return JsonResultPage
     * @author lyj
     * @since 2015-5-6
     */
    @RequestMapping(value = "/majorGroupList", method = RequestMethod.GET)
    @ResponseBody
    public JsonResultPage getAllSpecialty(@RequestParam("page") int pageNum,
                                          @RequestParam("pageSize") int pageSize,
                                          HttpServletRequest request) {
        Assert.isTrue(pageNum > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "当前页码"));
        Assert.isTrue(pageSize > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "每页条数"));

        //获取登录用户信息
        User userInfo = (User)((HttpSessionProxy)request.getSession()).getAttribute(sessionKey);

        Page<Specialty> page = specialtyGroupService.getAllSpecialty(pageNum, pageSize, userInfo);


        log.debug("获取专业群组列表");
        return new JsonResultPage(new Page(page.getTotal(), pageSize, pageNum, mapper.mapList(page.getItems(), SpecialtyInfoDto.class)));
    }


    /**
     * 获取专业群组明细头部
     *
     * @param specId 专业ID
     * @return JsonResultData
     * @author lyj
     * @since 2015-5-6
     */
    @RequestMapping(value = "/majorTop", method = RequestMethod.GET)
    @ResponseBody
    public JsonResultData getSpecialtyTop(@RequestParam("majorId") long specId,
                                          HttpServletRequest request) {
        Assert.isTrue(specId > 0, MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "专业ID"));

        //获取登录用户信息
        User userInfo = (User)((HttpSessionProxy)request.getSession()).getAttribute(sessionKey);

        Specialty specialty = specialtyGroupService.getSpecialtyTop(specId, userInfo);

        if (specialty != null) {
            log.debug("specialty != null");
            return new JsonResultData(mapper.map(specialty, SpecialtyInfoDto.class));
        }

        log.debug("获取专业群组明细头部");

        return new JsonResultData(false, "获取专业群组明细失败！");
    }





    /**
     * 专业群组资源统计
     * @param search 搜索关键字
     * @return JsonResult
     *
     * @author fanruiping
     * @since 2015-05-06
     */
    @RequestMapping(value = "/majorResourceStatistics", method = RequestMethod.GET)
    @ResponseBody
    public JsonResult majorResourceStatistics(@RequestParam String search,@RequestParam int tag){
        Assert.isTrue(tag == 0 || tag == 1,MessageFormat.format(MsgTemplate.ARG_VALIDATION_ERR, "标记"));

        //搜索关键字转码
        search = StringCodeUtil.urlParamTransCode(search, "utf-8");

        List<Map<String, Object>> groupResource = resourceService.getGroupResourceStatistics(tag, GroupType.SPEC_GROUP, search);

        log.debug("专业群组资源统计");
        return new JsonResultList<>(groupResource);
    }

    //</editor-fold>
}
